package com.lingjtx.common.pay.util;

import com.lingjtx.common.core.algorithm.RSAUtil;
import com.lingjtx.common.core.util.DateTimeUtil;
import com.lingjtx.common.pay.config.WePayConfigProperties;
import com.lingjtx.common.pay.model.wx.WeixinPayCertConfig;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Objects;
import java.util.UUID;

public class WePaySignatureUtil {

    public static String getToken(String method, String path, String body, WePayConfigProperties properties) {
        // 生成必要参数
        String nonceStr = UUID.randomUUID().toString();
        String timestamp = DateTimeUtil.getTimestampBySecond();

        // 构建待签名消息
        String message = buildMessage(method, path, timestamp, nonceStr, body);

        // 生成签名
        String signature = RSAUtil.sign(message, properties.getPriKey());

        return "WECHATPAY2-SHA256-RSA2048" + " " +
                "mchid=\"" + properties.getMchid() + "\"," +
                "nonce_str=\"" + nonceStr + "\"," +
                "timestamp=\"" + timestamp + "\"," +
                "serial_no=\"" + properties.getSerialNo() + "\"," +
                "signature=\"" + signature + "\"";
    }

    public static String buildMessage(String method, String path, String timestamp, String nonceStr, String body) {

        URL url = null;
        try {
            url = URI.create(path).toURL();
        } catch (MalformedURLException _) {
        }

        StringBuilder messageBuilder = new StringBuilder();

        // 构造 URL 的规范化路径和查询部分
        String canonicalUrl = Objects.requireNonNull(url).getPath();
        String query = url.getQuery();
        if (query != null) {
            canonicalUrl += "?" + query;
        }

        // 使用 StringBuilder 拼接字符串
        messageBuilder.append(method).append("\n")
                .append(canonicalUrl).append("\n")
                .append(timestamp).append("\n")
                .append(nonceStr != null ? nonceStr : "").append("\n") // 默认值处理
                .append(body != null ? body : "").append("\n"); // 默认值处理

        return messageBuilder.toString();
    }
}
